﻿using Aribaccio;
using BDPAutodetect.Client.ViewWindows.WindowDialog;
using BDPAutodetect.Device;
using BDPAutodetect.Mgrcore;
using BDPAutodetect.Models;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace BDPAutodetect.Client
{
    /// <summary>
    /// 指标设置管理视图模型类
    /// </summary>
    public partial class SettingTargetViewModel : BaseViewModel<UserControl>
    {
        /// <summary>
        /// 用户管理实例
        /// </summary>
        protected UserManager UserMgr { get; set; }
        /// <summary>
        /// 指标管理实例
        /// </summary>
        protected TargetSlaveManager TargetSlaveMgr { get; set; }
        /// <summary>
        /// 查询当前设备类型
        /// </summary>
        [ObservableProperty]
        protected DeviceTypeData deviceTypeItem;
        /// <summary>
        /// 查询设备类型集
        /// </summary>
        [ObservableProperty]
        protected ObservableCollection<DeviceTypeData> deviceTypeItems;
        /// <summary>
        /// 指标数据集
        /// </summary>
        [ObservableProperty]
        protected ObservableCollection<MTarget> targetItems;

        /// <summary>
        /// 构造函数
        /// </summary>
        public SettingTargetViewModel(UserManager argUserManager, TargetSlaveManager argTargetSlaveManager)
        {
            this.UserMgr = argUserManager;
            this.TargetSlaveMgr = argTargetSlaveManager;
            this.TargetItems = new ObservableCollection<MTarget>();
            this.DeviceTypeItems = new ObservableCollection<DeviceTypeData>();
            foreach (var item in DeviceTypeTable.Items)
            {
                if (item.DeviceType == DeviceType.None) continue;
                this.DeviceTypeItems.Add(item);
            }
            this.DeviceTypeItem = this.DeviceTypeItems.First();
        }

        /// <summary>
        /// 初始化加载权限编辑
        /// </summary>
        /// <returns></returns>
        protected async Task InitLoadPermission()
        {
            if (this.PowerPermission == null) return;
            var resultTaskPowers = this.UserMgr.GetUserPowers(this.PowerPermission.Power.ID);
            await resultTaskPowers.ConfigureAwait(false);
            if (resultTaskPowers != null && resultTaskPowers.Result != null && resultTaskPowers.Result.Count > 0)
            {
                this.IsVisibilityPermission = Visibility.Visible;
            }
        }

        /// <summary>
        /// 页面初始化加载事件
        /// </summary>
        [RelayCommand]
        public async Task ExecuteLoaded()
        {
            if (this.IsLoaded) return;
            //获取编辑权限
            var resultTask = this.InitLoadPermission();
            await resultTask.ConfigureAwait(false);
            //标记初始化加载完成
            this.IsLoaded = true;

            //初始化加载数据
            resultTask = this.ExecuteQuery();
            await resultTask.ConfigureAwait(false);
        }

        /// <summary>
        /// 编辑更新事件
        /// </summary>
        /// <param name="argTarget">指标信息</param>
        /// <returns></returns>
        [RelayCommand]
        public async Task ExecuteEditor(MTarget argTarget)
        {
            SettingTargetEditorDialog editorDialog = new SettingTargetEditorDialog(argTarget, this.DeviceTypeItems);
            bool? bResult = editorDialog.ShowDialog();
            if (!bResult.HasValue || !bResult.Value) return;
            if (editorDialog.DialogResultData == null) return;

            //更新数据库
            var result = this.TargetSlaveMgr.UpdateTarget(editorDialog.DialogResultData);
            await result.ConfigureAwait(false);
        }

        /// <summary>
        /// 查询命令事件
        /// </summary>
        /// <returns></returns>
        [RelayCommand]
        public async Task ExecuteQuery()
        {
            if (!this.IsExecutedIdle) return;
            //设置非空闲忙碌中
            this.IsExecutedIdle = false;
            var resultTask = this.QueryData(this.DeviceTypeItem.DeviceType);
            await resultTask.ConfigureAwait(false);
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        public async Task QueryData(DeviceType argDeviceType)
        {
            await Task.Factory.StartNew(() =>
            {
                try
                {
                    this.TargetItems.Clear();
                    var resultDatas = this.TargetSlaveMgr.GetTargets(argDeviceType);
                    if (resultDatas != null)
                    {
                        var orderDatas = resultDatas.OrderBy(v => v.SerialNo);
                        foreach (var item in orderDatas)
                        {
                            this.TargetItems.Add(item);
                        }
                    }
                }
                finally
                {
                    this.IsExecutedIdle = true;
                }
            }, new CancellationTokenSource().Token, TaskCreationOptions.None, base.syncContextTask);
        }
    }
}
